#!/usr/bin/python

source_dir="/me/MiChangSheng_Mod/misc/Taiwu\\!"
workshop_dir="/me/steamapps/workshop/content/838350"
LICENSE="/me/MiChangSheng_Mod/LICENSE"
# source_dir="" # 如果你没有源码目录，应该取消这一行的注释 如果你是windows，你需要参考旧版Mod自己改引用dll的位置

if __name__ == '__main__':
  import os
  import sys
  import multiprocessing
  from shutil import copyfile, copy
  Force_Pass=False
  cwd = os.path.dirname(__file__) if os.path.dirname(__file__)!='' else os.getcwd()
  os.chdir(cwd)
  os.system("rm -f ../Logs/*") # 删除太吾的Log
  list=[]
  pytime=os.path.getmtime("time.python.stamp") if os.path.exists('time.python.stamp') else 0.0
  # pytimex=pytime
  for i in os.listdir():
    if i[-3:]=='.py' and i[-14:]!=sys.argv[0][-14:] and os.path.getmtime(i)>pytime:
      print("execute "+i)
      os.system("python "+i)
      # pytimex=max(os.path.getmtime(i),pytimex)
  if (os.path.getmtime('NpcScan/Aux-CharacterData-common.python.CS') if os.path.exists('NpcScan/Aux-CharacterData-common.python.CS') else 0.0) < (os.path.getmtime('NpcScan/Aux-CharacterData-common.CS') if os.path.exists('NpcScan/Aux-CharacterData-common.CS') else pytime+1):
    print("execute 'npcscan-gen.py' since 'NpcScan/Aux-CharacterData-common.CS' is modified")
    os.system('python npcscan-gen.py')
  with open("time.python.stamp",'w') as f:
    # f.write(str(pytimex))
    pass
  for i in os.listdir():
    try:
      os.chdir(i)
      copyfile(LICENSE,os.getcwd()+'/LICENSE')
      cstime=0.0
      dlltime=0.0
      for j in os.listdir():
        if j[-3:].lower()==".cs":
          cstime=max(cstime,os.path.getmtime(j))
        elif j[-3:].lower()=="dll":
          dlltime=os.path.getmtime(j) if dlltime==0.0 else min(dlltime,os.path.getmtime(j))
      if cstime > dlltime:
        print(os.getcwd())
        print("    compile dlls in `"+i+"` since it is newer than `*.dll`s")
        Force_Pass=True
        for j in os.listdir():
          if j[-3:]==".cs" and j.count('.')==1:
            with open(j) as f:
              i=multiprocessing.Process(target=os.system,args=('/'.join(f.readline().split('/')[2:]),))
              i.start()
              list.append(i)
      os.chdir('..')
    except FileNotFoundError as e:
      continue
    except NotADirectoryError:
      continue
  for i in list:
    i.join()
  #
  # 提交修改
  #
  if len(source_dir)>0:
    os.system("7z a -r ../Mod.7z . >/dev/null")
    os.system("rm -f */LICENSE")
    os.system("cp -r . "+source_dir)
    os.system("find "+source_dir+" -iname '*.dll' -delete")
    os.chdir(source_dir.replace("\\",''))
    os.system("git add .")
    # commit 就手工来吧
  #
  # 工坊相关-等待读取
  #
  try:
    Force_Pass or input("\n按回车上传，Ctrl+C/Ctrl+D取消上传\n")
    os.chdir(cwd)
    for i in os.listdir():
      try:
        with open(i+"/Config.lua") as f:
          g=f.readlines()
          try:
            fileid=[g for g in g if '--workshop_only    FileId' in g][0].split('=')[1].split(',')[0].strip()
            title="=".join([g for g in g if 'Title' in g][0].split('=')[1:]).split(',')[0].strip()
            #print('复制 '+i+'('+title+') 到 '+workshop_dir+'/'+fileid)
            os.system('rm \''+i+'/Settings.Lua\' 2>/dev/null')
            os.system('cp -r \''+i+'/\'* \''+workshop_dir+'/'+fileid+'\'')
            os.system("""sed -i 's/--workshop_only//g' """ + "'" + workshop_dir+'/'+fileid+'/Config.lua\'')
            copyfile(LICENSE,workshop_dir+'/'+fileid+'/LICENSE')
          except IndexError:
            print("文件夹 "+i+" 不是steam mod")
            continue
      except FileNotFoundError:
        print("文件 "+i+"/Config.lua不存在")
        continue
      except NotADirectoryError:
        # print(i+"不是文件夹")
        continue
    print()
    os.chdir(workshop_dir)
    for i in os.listdir():
      try:
        #print(os.getcwd()+'/'+i)
        if os.path.exists(i+'/MySettings.Lua') and os.path.exists(i+'/LICENSE'):
          with open(i+"/Config.lua") as f:
            g=f.readlines()
            #print(os.path.exists(i+'/MySettings.Lua'))
            #print(os.path.exists(i+'/LICENSE'))
            Force_Pass or print("待上传 "+os.getcwd()+'/'+i+" -- "+"=".join([g for g in g if 'Title' in g][0].split('=')[1:]).split(',')[0].strip())
            if os.path.exists(i+'/Settings.Lua'):
              if os.path.getsize(i+'/MySettings.Lua')>10:
                with open(i+'/MySettings.Lua') as f:
                  if '\t' in f.read():
                    os.remove(i+'/MySettings.Lua')
                    os.rename(i+'/Settings.Lua',i+'/MySettings.Lua')
              os.remove(i+'/Settings.Lua')
      except FileNotFoundError:
        continue
      except NotADirectoryError:
        continue
  except EOFError:
    print("捕获到Ctrl+D，停止上传")
  except KeyboardInterrupt:
    print("捕获到Ctrl+C，停止上传")
  #
  # 工坊相关-完成上传
  #
  try:
    Force_Pass or input("\n按回车恢复，Ctrl+C/Ctrl+D取消恢复\n")
    os.chdir(workshop_dir)
    for i in os.listdir():
      try:
        if os.path.exists(i+'/MySettings.Lua') and os.path.exists(i+'/LICENSE'):
          copyfile(i+'/MySettings.Lua',i+'/Settings.Lua')
          Force_Pass or print("已恢复 "+os.getcwd()+'/'+i)
      except FileNotFoundError:
        continue
      except NotADirectoryError:
        continue
  except EOFError:
    print("捕获到Ctrl+D，停止上传")
  except KeyboardInterrupt:
    print("捕获到Ctrl+C，停止上传")
